package TCP;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SocketServer_demo {
public static void main(String[] args) throws IOException {
	ServerSocket server=new ServerSocket(8888);//服务器设定端口号
	ExecutorService pool=Executors.newCachedThreadPool();//使用线程池来处理并行进程
	while(true)
	{
	Socket socket=server.accept();//接受Socket访问
	pool.submit(new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				InputStream is=socket.getInputStream();//生成IO输入流
				File file=new File("d:\\target");//放置上传文件位置
				if(!file.exists())
					file.mkdirs();
				String filename="go"+System.currentTimeMillis()+Math.random()*10000+".jpg";//使用随机数防止文件重复
				FileOutputStream fos=new FileOutputStream(file+"\\"+filename);//建立文件输出流
				int len=0;
				byte[]bytes=new byte[1024];
				while((len=is.read(bytes))!=-1)//读取文件
					fos.write(bytes,0,len);//向文件输出流输入
			   	socket.getOutputStream().write("successed".getBytes());//向从客户端得到的IO输出流以字节流形式发送成功信息
			    fos.close();
			}
			catch(IOException e) {e.printStackTrace();}
			
			finally {

				try {
					socket.close();//关闭访问
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	});
	
	
	}
}
}
